<?php

namespace App\Http\Controllers\Log;

use App\Http\Controllers\Controller;
use App\Models\Common\ApiResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use function storage_path;

class StorageLogController extends Controller
{
    public function parkingFiles(Request $request): array
    {
        // 日志文件夹的路径
        $logDirectory = storage_path('logs/device');

        $list = [];
        // 检查目录是否存在
        if (File::exists($logDirectory)) {
            // 获取目录中的所有文件名
            $files = File::allFiles($logDirectory);

            // 提取文件名
            array_map(function ($file) use (&$list) {
                $fileName = $file->getFilename();
                if (strpos($fileName, 'parking') !== false) {
                    $list[] = substr($fileName, 8, 10);
                }
            }, $files);
        }

        return ApiResponse::success($list);
    }

    public function downloadLogFile(Request $request)
    {
        $filename = $request->get('filename');
        // 验证文件名
        if (!preg_match('/^[a-zA-Z0-9\.\-]+$/', $filename)) {
            return ApiResponse::fail('文件不存在');
        }

        if (!check_date($filename, ['Y-m-d'])) {
            return ApiResponse::fail('文件名错误');
        }

        // 日志文件夹的路径
        $logDirectory = storage_path('logs/device');

        // 构建完整的文件路径
        $filePath = $logDirectory . '/parking-' . $filename . '.log';

        // 检查文件是否存在
        if (!File::exists($filePath)) {
            return ApiResponse::fail('文件已不存在');
        }

        // 返回文件下载响应
        return response()->download($filePath);
    }
}
